<script setup>
import { getPhoneNumber, login, getUserInfo, supplementUserInfo } from '@/api/profile';

const state = reactive({
  sourceUrl: '/pages/home/home',
  isChoosePro: false
});

const handleCheckboxChange = (e) => {
  state.isChoosePro = e.detail.value.length > 0;
};

onLoad((options) => {
  if (options && options.from) {
    state.sourceUrl = options.from || '/pages/home/home';
  } else {
    state.sourceUrl = '/pages/home/home';
  }
});

onShow(() => {
  userLogin(null);
});

const onGetPhoneNumber = async (e) => {
  if (!state.isChoosePro) {
    uni.showToast({
      title: '请阅读并同意《诚电快充隐私协议》',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  if (e.detail.errMsg.includes('fail')) {
    return;
  }
  const { iv, encryptedData } = e.detail;
  const deviceId = uni.getStorageSync('deviceId');
  const loginResult = await uni.login();
  if (loginResult.code) {
    await getPhoneNumber(loginResult.code, encryptedData, iv, deviceId);
    navigateAfterAuth(state.sourceUrl);
  }
};

const navigateAfterAuth = (sourceUrl) => {
  const deviceId = uni.getStorageSync('deviceId');
  let url = sourceUrl || '/pages/home/home';

  if (deviceId) {
    url = '/pages/rentRule/rentRule';
  }

  if (url) {
    uni.redirectTo({ url }).catch((err) => {
      console.error(`导航失败: ${err.errMsg}`);
      uni.reLaunch({ url: '/pages/home/home' });
    });
  } else {
    uni.reLaunch({ url: '/pages/home/home' });
  }
};

const handleLogin = () => {
  return new Promise((resolve) => {
    uni.login({
      success: (res) => {
        if (res.code) {
          login(res.code).then((res) => {
            console.log('--------->', res);
            uni.setStorageSync('Authorized-Token', res.data.token); // 保存 token
            resolve(res.data);
          });
        } else {
          resolve(undefined);
        }
      }
    });
  });
};

const handleGetUserInfo = () => {
  return new Promise((resolve, reject) => {
    uni.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  });
};

const handleSaveUserInfo = (userInfo) => {
  return new Promise((resolve) => {
    supplementUserInfo(userInfo).then((res) => {
      resolve(res.data);
    });
  });
};

const handleGetInfo = () => {
  return new Promise((resolve) => {
    getUserInfo().then((res) => {
      getApp().globalData.userInfo = res.data;
      resolve(res.data);
    });
  });
};

const userLogin = async (userInfo) => {
  if (userInfo == null) {
    let wxLoginResult = await handleLogin();
    if (!wxLoginResult) {
      return;
    }
    let info = await handleGetInfo();
    const { mobile, nickName } = info;

    if (nickName !== '') {
      navigateAfterAuth(state.sourceUrl);
      return;
    }
    if (nickName === '') {
      return;
    }
  }

  userInfo = await handleGetUserInfo();
  if (!userInfo) {
    return;
  }

  let saveUserInfoResult = await handleSaveUserInfo(userInfo);
  if (!saveUserInfoResult) {
    return;
  }
  getApp().globalData.userInfo = saveUserInfoResult;
  navigateAfterAuth(state.sourceUrl);
};

const navigateToPage = (page) => {
  console.log(page);
  uni.navigateTo({
    url: page,
    fail: (err) => {
      console.error(`导航失败:${err.errMsg}`);
    }
  });
};
</script>

<template>
  <view class="viewport">
    <view class="logo">
      <image src="@/static/images/icon_logo.png"></image>
    </view>
    <view class="login">
      <view class="box">
        <view class="tip">请确认授权以下信息</view>
        <view class="tips_2">• 获得你的公开信息(昵称、头像等)</view>
        <view class="tips_2">• 通过微信向你展示订单信息、发送服务提醒</view>
        <view class="tips_2">• 获取手机号方便租借售后问题处理</view>
      </view>
      <button class="button_phone" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
        <image src="@/static/images/icon_phone.png" class="icon_phone" />
        微信手机号快捷登录
      </button>
      <checkbox-group @change="handleCheckboxChange" class="tips">
        <label class="label">
          <checkbox style="transform: scale(0.7)" />
          <view>登录/注册即视为你同意</view>
          <text class="tips_1" @click="navigateToPage('/pages/privacy/privacy')">《诚电快充隐私协议》</text>
        </label>
      </checkbox-group>
    </view>
  </view>
</template>

<style lang="scss">
.viewport {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 100vh;

  .logo {
    display: flex;
    align-items: center;
    flex: 1;
    text-align: center;
    image {
      width: 420rpx;
      height: 220rpx;
    }
  }

  .login {
    display: flex;
    flex-direction: column;
    flex: 1;
    width: 100%;
    .box {
      border-top: 2rpx solid #ececec;
      .tip {
        margin: 58rpx 0 0 80rpx;
        font-size: 36rpx;
        font-weight: bold;
        color: #202020;
      }
      .tips_2 {
        margin: 30rpx 0 0 80rpx;
        font-size: 30rpx;
        font-weight: 400;
        color: #808080;
      }
    }
    .button_phone {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 40rpx;
      width: 80%;
      height: 90rpx;
      font-size: 28rpx;
      border-radius: 50rpx;
      color: #fff;
      background-color: rgba(7, 193, 96, 1);

      .icon_phone {
        margin-right: 15rpx;
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        vertical-align: sub;
      }
    }

    .tips {
      display: flex;
      justify-content: center;
      margin-top: 20rpx;
      font-size: 26rpx;
      color: #999;
      .label {
        display: flex;
        align-items: center;
      }
      .tips_1 {
        font-size: 26rpx;
        color: rgba(7, 193, 96, 1);
      }
    }
  }
}
</style>
